package com.example.mardan_demo1.service.impl;

import com.example.mardan_demo1.mapper.WuZhiHuaHuiYiMapper;
import com.example.mardan_demo1.pojo.PageBean;
import com.example.mardan_demo1.pojo.Result;
import com.example.mardan_demo1.pojo.WuZhiHuaHuiYi.DevicePojo;
import com.example.mardan_demo1.pojo.WuZhiHuaHuiYi.HuiYi;
import com.example.mardan_demo1.pojo.WuZhiHuaHuiYi.YiTi;
import com.example.mardan_demo1.pojo.Yaopin;
import com.example.mardan_demo1.service.WuZhiHuaHuiYiService;
import com.example.mardan_demo1.utils.IpUtils;
import com.example.mardan_demo1.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author:买尔旦江 ×@CreateTime: 2025-02-09
 * @Description: 无纸化会议业务实现类
 * @Version: 1.0
 */

@Service
public class WuZhiHuaHuiYiServiceImpl implements WuZhiHuaHuiYiService {
    @Autowired
    private WuZhiHuaHuiYiMapper wuZhiHuaHuiYiMapper;
    private IpUtils ipUtils;
    public String getUserNameByToken() {
        Map<String,Object> userInfo = ThreadLocalUtil.get();
        String userName = (String) userInfo.get("username");
        return userName;
    }
    public Integer getUserIdByToken() {
        Map<String,Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        return userId;
    }
    @Override
    public Result addHuiYi(HuiYi huiYi) {
        // 获取操作人的id
        huiYi.setCreated_by(getUserIdByToken().toString());
        huiYi.setState("1");
        huiYi.setHidden("0");
        long huiYiId = wuZhiHuaHuiYiMapper.addHuiYi(huiYi);
        return Result.success(huiYi);
    }

    @Override
    public Result getHuiYiById(Integer id) {
        HuiYi huiYi = wuZhiHuaHuiYiMapper.getHuiYiById(id);
        if(huiYi == null) {
            return Result.error("该会议不存在");
        }
        return Result.success(huiYi);
    }

    @Override
    public Result getHuiYiList(Integer pageSize, Integer pageNum, String cname, String state) {
        // 创建pageBean对象
        PageBean<HuiYi> pb = new PageBean<>();
        // 开启分页查询，自动拼接到sql语句中，不需要在sql中手动写入
        PageHelper.startPage(pageNum, pageSize);
        // 获取查询者的id，只查询id创建的数据
        List<HuiYi> as = wuZhiHuaHuiYiMapper.getlist(cname, state);
        // 数据列表和总数、页数合并
        Page<HuiYi> p = (Page<HuiYi>) as;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }

    @Override
    public Result addYiTi(YiTi yiti) {
        //设置创建人
        yiti.setCreated_by(getUserIdByToken().toString());
        // 校验会议是否存在
        HuiYi huiyi = wuZhiHuaHuiYiMapper.getHuiYiById(Integer.valueOf(yiti.getHuiyi_id()));
        if(huiyi == null) {
            return Result.error("该会议不存在");
        }
        wuZhiHuaHuiYiMapper.addYiTi(yiti);
        return Result.success("新增成功");
    }

    @Override
    public Result getYiTiByHuiYiId(Integer id) {
        // 查看会议是否存在
        HuiYi huiyi = wuZhiHuaHuiYiMapper.getHuiYiById(id);
        if(huiyi == null) {
            return Result.error("该会议不存在");
        }
        // 查询会议下面的所有议题
        List<YiTi> yiTiList = wuZhiHuaHuiYiMapper.getYiTiByHuiYiId(id);
        return Result.success(yiTiList);
    }

    @Override
    @Transactional
    public Result deleteHuiYiById(Integer id) {
//        只能删除自己创建的会议
        HuiYi huiyi = wuZhiHuaHuiYiMapper.findHuiYiByUserIdAndHuiYiId(id, getUserIdByToken());
        if(huiyi == null) {
            return Result.error("您无权删除该会议");
        }
        wuZhiHuaHuiYiMapper.deleteHuiYiById(id);
        // 同时删除会议相关议题
        wuZhiHuaHuiYiMapper.deleteYiTiByHuiYiId(id);
        return Result.success(1);
    }

    @Override
    public Result getYiTiById(Integer id) {
        YiTi yiti = wuZhiHuaHuiYiMapper.getYiTiById(id);
        if(yiti == null) {
            return Result.error("该议题不存在");
        }
        return Result.success(yiti);
    }

    @Override
    public Result jieShuHuiYi(Integer id) {
        // 获取会议查看是否存在并且是否由这个人创建
        HuiYi huiyi = wuZhiHuaHuiYiMapper.getHuiYiById(id);
        if(huiyi == null) {
            return Result.error("该会议不存在");
        }
        // 只有创建者可以结束会议
        String createrId = huiyi.getCreated_by();
        String userIdFromToken = getUserIdByToken().toString();

        if(!createrId.equals(userIdFromToken)) {
            return Result.error("只有创建人才能结束会议");
        }
        huiyi.setState("0");
        wuZhiHuaHuiYiMapper.updateHuiYi(huiyi);
        return Result.success(1);
    }

    @Override
    public Result huiFuHuiYi(Integer id) {
        // 获取会议查看是否存在并且是否由这个人创建
        HuiYi huiyi = wuZhiHuaHuiYiMapper.getHuiYiById(id);
        if(huiyi == null) {
            return Result.error("该会议不存在");
        }
        // 只有创建者可以结束会议
        String createrId = huiyi.getCreated_by();
        String userIdFromToken = getUserIdByToken().toString();

        if(!createrId.equals(userIdFromToken)) {
            return Result.error("只有创建人才能恢复会议");
        }
        huiyi.setState("1");
        wuZhiHuaHuiYiMapper.updateHuiYi(huiyi);
        return Result.success(1);
    }

    @Override
    public Result updateHuiYi(HuiYi huiYi) {
        // 查看会议是否存在并且是否由该用户创建
        HuiYi huiYiFromDb = wuZhiHuaHuiYiMapper.getHuiYiById((int) huiYi.getId());
        if(huiYiFromDb == null) {
            return Result.error("该会议不存在");
        }
        String createrId = huiYiFromDb.getCreated_by();
        String userIdFromToken = getUserIdByToken().toString();
        if(!createrId.equals(userIdFromToken)) {
            return Result.error("只有创建人才能修改会议");
        }
        wuZhiHuaHuiYiMapper.updateHuiYi(huiYi);
        return Result.success("修改成功");
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result deleteYiTiById(Integer id) {
        // 先查看这个议题是否存在并且是否由这个人创建
        YiTi yitiFromDb = wuZhiHuaHuiYiMapper.findYiTiById(id);
        if(yitiFromDb == null) {
            return Result.error("该议题不存在");
        }
        String createrId = yitiFromDb.getCreated_by();
        String userIdFromToken = getUserIdByToken().toString();
        if(!createrId.equals(userIdFromToken)) {
            return Result.error("只有创建人才能删除该议题");
        }
        wuZhiHuaHuiYiMapper.deleteYiTiById(id);
        return Result.success("删除成功");
    }

    /**
     * @param yiti
     * @return
     */
    @Override
    public Result insertTopicsInOrder(YiTi yiti) {
        // 先判断是否存在会议
        HuiYi huiyiFromDb = wuZhiHuaHuiYiMapper.getHuiYiById(Integer.valueOf(yiti.getHuiyi_id()));
        if(huiyiFromDb == null) {
            return Result.error("该会议不存在");
        }
        // 判断是否由创建人操作
        String createrId = huiyiFromDb.getCreated_by();
        String userIdFromToken = getUserIdByToken().toString();
        if(!createrId.equals(userIdFromToken)) {
            return Result.error("只有创建人才能添加议题");
        }
        // 查看数据库由多少个议题，新增议题会插入到最后
        int count = wuZhiHuaHuiYiMapper.getYiTiByHuiYiId(Integer.valueOf(yiti.getHuiyi_id())).size();
        yiti.setYsort(String.valueOf(count + 1));
        wuZhiHuaHuiYiMapper.addYiTi(yiti);
        return Result.success("添加成功");

    }

    /**
     * @param topicId
     * @return
     */
    @Override
    @Transactional
    public Result moveUpTopics(Integer topicId) {
        // 查看当前排序，如果在第一位返回无法上移
        YiTi yitiFromDb = wuZhiHuaHuiYiMapper.findYiTiById(topicId);
        if(yitiFromDb == null) {
            return Result.error("该议题不存在");
        }
        if(yitiFromDb.getYsort().equals(1)) {
            return Result.success("已在第一位无法继续上移");
        }
        // 如果能继续上移就找到上面的议题与他交换顺序
        YiTi upperYiti = wuZhiHuaHuiYiMapper.findYiTiByHuiYiIdAndSort(yitiFromDb.getHuiyi_id(), Integer.parseInt(yitiFromDb.getYsort())-1);
        if (upperYiti == null) {
            return Result.success("上一位议题不存在");
        }
        String temp = upperYiti.getYsort();
        upperYiti.setYsort(yitiFromDb.getYsort());
        yitiFromDb.setYsort(temp);
        wuZhiHuaHuiYiMapper.updateYiTi(yitiFromDb);
        wuZhiHuaHuiYiMapper.updateYiTi(upperYiti);
        return Result.success(1);
    }

    /**
     * @param topicId
     * @return
     */
    @Override
    public Result moveDownTopics(Integer topicId) {
        // 查看当前排序，如果在最后一位就无法继续下移
        YiTi yitiFromDb = wuZhiHuaHuiYiMapper.findYiTiById(topicId);
        if(yitiFromDb == null) {
            return Result.error("该议题不存在");
        }
        int count = wuZhiHuaHuiYiMapper.getYiTiByHuiYiId(Integer.valueOf(yitiFromDb.getHuiyi_id())).size();
        if(yitiFromDb.getYsort().equals(count + 1)) {
            return Result.success("已在最后一位无法继续下移");
        }
        // 如果能继续上移就找到上面的议题与他交换顺序
        YiTi upperYiti = wuZhiHuaHuiYiMapper.findYiTiByHuiYiIdAndSort(yitiFromDb.getHuiyi_id(), Integer.parseInt(yitiFromDb.getYsort())+1);
        if (upperYiti == null) {
            return Result.success("下一位议题不存在");
        }
        String temp = upperYiti.getYsort();
        upperYiti.setYsort(yitiFromDb.getYsort());
        yitiFromDb.setYsort(temp);
        wuZhiHuaHuiYiMapper.updateYiTi(yitiFromDb);
        wuZhiHuaHuiYiMapper.updateYiTi(upperYiti);
        return Result.success(1);
    }

    /**
     * @param topicId
     * @return
     */
    @Override
    public Result deleteTopicAndSort(Integer topicId) {
//        删除议题后将后面的议题的顺序都调整
        YiTi yitiFromDb = wuZhiHuaHuiYiMapper.findYiTiById(topicId);
        if(yitiFromDb == null) {
            return Result.error("该议题不存在");
        }
//        先保存议题的sort序号
        int currentSort = Integer.parseInt(yitiFromDb.getYsort());
        wuZhiHuaHuiYiMapper.deleteYiTiById((int) yitiFromDb.getId());
//        获取所有议题，编辑并且保存
        List<YiTi>  yitiList = wuZhiHuaHuiYiMapper.getYiTiByHuiYiId(Integer.valueOf(yitiFromDb.getHuiyi_id()));
        // yitiList按照ysort属性排序


        // 循环修改排序
//        for(int i = 0; i < yitiList.size(); i++) {
//            if(yitiList.get(i).getId().equals(yitiFromDb.getId())) {
//                continue;
//            }
//            yitiList.get(i).setYsort(String.valueOf(i+1));
//            wuZhiHuaHuiYiMapper.updateYiTi(yitiList.get(i));
//        }
        for(int i = 0; i < yitiList.size(); i++) {
            yitiList.get(i).setYsort(String.valueOf(i+1));
            wuZhiHuaHuiYiMapper.updateYiTi(yitiList.get(i));
        }
        return Result.success(1);

    }

    @Override
    public Result getMeetingListByMacAddresses() {
        return Result.success();
    }

    @Override
    public Result getMeetingListByIPAddress(HttpServletRequest request) {
        String ipAddress = ipUtils.getClientIp(request);
        DevicePojo deviceFromDb = wuZhiHuaHuiYiMapper.getDeviceByIpAddress(ipAddress);
        if(deviceFromDb == null) {
            return Result.error("该设备没有被授权，请联系管理员");
        }
        if(!deviceFromDb.getStatus().equals("1")) {
            return Result.error("该设备已被禁用，请联系管理员");
        }
        if(deviceFromDb.getStatus().equals("1")) {

            List<HuiYi> as = wuZhiHuaHuiYiMapper.getListForClient();

            return Result.success(as);
        }
        return Result.success(ipAddress);
    }

    /**
     * @param device
     * @return
     */
    @Override
    public Result addDevice(DevicePojo device) {
        String userId = getUserIdByToken().toString();
        device.setCreated_by(userId);
        wuZhiHuaHuiYiMapper.addDevice(device);
        return Result.success("1");
    }

    /**
     * @param device
     * @return
     */
    @Override
    public Result updateDeviceInfo(DevicePojo device) {
        DevicePojo deviceFromDb = wuZhiHuaHuiYiMapper.getDeviceById((int) device.getId());
        if(deviceFromDb == null) {
            return Result.error("该设备不存在");
        }
        wuZhiHuaHuiYiMapper.updateDevice(device);
        return Result.success("1");
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result deleteDeviceInfo(Integer id) {
        DevicePojo deviceFromDb = wuZhiHuaHuiYiMapper.getDeviceById(id);
        if(deviceFromDb == null) {
            return Result.error("该设备不存在");
        }
       Integer deviceId = wuZhiHuaHuiYiMapper.deleteDeviceById(id);
       return Result.success(deviceId);
    }

    /**
     * @param ip
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getDeviceList(String ip, Integer pageNum, Integer pageSize) {
        //分页查询
        // 创建pageBean对象
        PageBean<DevicePojo> pb = new PageBean<>();
        // 开启分页查询，自动拼接到sql语句中，不需要在sql中手动写入
        PageHelper.startPage(pageNum, pageSize);
        // 获取查询者的id，只查询id创建的数据
        List<DevicePojo> as = wuZhiHuaHuiYiMapper.getDeviceList(ip);
        // 数据列表和总数、页数合并
        Page<DevicePojo> p = (Page<DevicePojo>) as;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result getDeviceInfoById(Integer id) {
        DevicePojo deviceFromDb = wuZhiHuaHuiYiMapper.getDeviceById(id);
        if(deviceFromDb == null) {
            return Result.error("该设备不存在");
        }
        DevicePojo device = wuZhiHuaHuiYiMapper.getDeviceById(id);
        return Result.success(device);
    }

    @Override
    public Result getIpAddressForClient(HttpServletRequest request) {
        String ipAdress = ipUtils.getClientIp(request);
        return Result.success(ipAdress);
    }

    /**
     * @param request
     * @return
     */
    @Override
    public Result getMeetingListByShouquanYonghu(HttpServletRequest request) {
        // 检查设备是否授权
        String ipAdress = ipUtils.getClientIp(request);
        DevicePojo deviceFromDb = wuZhiHuaHuiYiMapper.getDeviceByIpAddress(ipAdress);
        if(deviceFromDb == null) {
            return  Result.success("设备未被授权，请联系管理员");
        }
        if(!deviceFromDb.getStatus().equals("1")) {
            return Result.success("设备已被禁用，请联系管理员");
        }
        List<HuiYi> as = wuZhiHuaHuiYiMapper.getMeetingListByShouquanYonghu();
        return Result.success(as);

    }


}
